<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    class="order-selection-dialog"
    :close-on-click-modal="false"
    :width="type == 1 ? '1050px' : '1200px'"
    :before-close="handleClose"
    destroy-on-close
  >
    <!-- 筛选区域 -->
    <div class="filter-card" shadow="never">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        label-width="80px"
        @submit.prevent="handleQuery"
        size="default"
      >
        <el-row :gutter="20">
          <el-form-item label="订单号" prop="orderId">
            <el-input
              v-model="queryParams.orderId"
              placeholder="请输入订单号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="">
            <el-input
              v-model="queryParams.receiverPhone"
              placeholder="请输入手机号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="客户姓名" prop="receiverName">
            <el-input
              v-model="queryParams.receiverName"
              placeholder="请输入客户姓名"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-button class="ml-10" type="primary" @click="handleQuery" :loading="loading">
            搜索
          </el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="orderList"
      v-loading="loading"
      highlight-current-row
      style="width: 100%; margin-top: 16px; cursor: pointer"
      height="600"
    >
      <el-table-column prop="orderId" label="订单信息" width="320">
        <template #default="{ row }">
          <!-- 订单信息 -->
          <RowSlots v-if="type == 1" slotName="orderSlot" :row="row" />
          <!-- 复购单 -->
          <RowSlots v-else slotName="repeatOrderSlot" :row="row" />
        </template>
      </el-table-column>
      <el-table-column prop="re" label="客户信息" width="220">
        <template #default="{ row }">
          <RowSlots v-if="type == 1" slotName="logisticsSlot" :row="row" />
          <RowSlots v-else slotName="repeatLogisticsSlot" :row="row" />
        </template>
      </el-table-column>
      <el-table-column prop="salesman" label="业务员" width="120">
        <template #default="{ row }">
          <RowSlots slotName="salesmanSlot" :row="row" />
        </template>
      </el-table-column>
      <!-- 订单信息 复购才有 -->
      <el-table-column prop="repeatDosage" label="复购商品数量" v-if="type == 2" width="150">
        <template #default="{ row }">
          <RowSlots slotName="repeatDosageSlot" :row="row" :goodsTypes="goodsTypes" />
        </template>
      </el-table-column>

      <el-table-column prop="orderTime" label="下单时间" width="240" :formatter="dateTimeFormatter">
        <template #default="{ row }">
          <RowSlots slotName="orderTimerSlot" :row="row" />
        </template>
      </el-table-column>
      <el-table-column prop="orderType" label="操作" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="confirmSelection(scope.row)">
            选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        layout="prev, pager, next"
        :total="total"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElMessage
} from 'element-plus';
import { listRepeatPurchaseOrder } from '../../api/platformOrders/orders/repeatPurchaseOrder';
import { listOrder } from '../../api/platformOrders/orders/list';
interface Props {
  type: 1 | 2; // 严格限定为 1 或 2
  goodsTypes: any[];
}

const props = withDefaults(defineProps<Props>(), {
  type: 1,
  goodsTypes: [] as any
});

const emit = defineEmits(['select']);

interface OrderItem {
  id: number | string;
  orderId: string;
  receiverName: string;
  receiverPhone: string;
  orderAmount: number;
  orderTime: string; // ISO 格式字符串
  status: number; // 假设状态用数字表示
}

// ------------------------ 响应式数据 ------------------------
const dialogVisible = ref(false);
const loading = ref(false);
const queryFormRef = ref();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderId: '',
  receiverPhone: '',
  receiverName: ''
});

// 订单列表与总数
const orderList = ref<OrderItem[]>([]);
const total = ref(0);

// 当前选中订单
const selectedOrder = ref<OrderItem | null>(null);

// ------------------------ 计算属性 ------------------------
const dialogTitle = computed(() => {
  return props.type == 1 ? '选择普通订单' : '选择复购订单';
});

// ------------------------ 方法 ------------------------
// 格式化日期时间
const dateTimeFormatter = (_row: OrderItem, _column: any, cellValue: string) => {
  return new Date(cellValue).toLocaleString('zh-CN');
};

// 获取订单列表
const getList = async () => {
  loading.value = true;
  try {
    let res;
    if (props.type == 1) {
      res = await listOrder(queryParams);
    } else {
      res = await listRepeatPurchaseOrder(queryParams);
    }
    loading.value = false;

    if (res.code == 200) {
      orderList.value = res.rows || [];
      total.value = parseInt(res.total || 0);
      // 如果列表为空，清空选中
      if (orderList.value.length == 0) {
        selectedOrder.value = null;
      }
    } else {
      ElMessage.error(res.msg || '获取数据失败');
      orderList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('请求失败，请稍后重试');
    orderList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1; // 重置到第一页
  getList();
};

// 重置查询
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  queryParams.pageNum = 1;
  getList();
};

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
  queryParams.pageSize = newSize;
  getList();
};

// 处理当前页变化
const handleCurrentChange = (newPage: number) => {
  queryParams.pageNum = newPage;
  getList();
};

// 确认选择
const confirmSelection = (row: OrderItem) => {
  // 抛出选中的订单数据
  emit('select', row);
  // 关闭弹窗
  dialogVisible.value = false;
};

// 关闭弹窗 (包括点击遮罩层、右上角X、取消按钮)
const handleClose = () => {
  dialogVisible.value = false;
  // 可选：重置状态
  // selectedOrder.value = null
  // queryParams.pageNum = 1
  // queryParams.pageSize = 10
};

// ------------------------ 暴露给父组件的方法 ------------------------
// 定义一个方法，供父组件通过 ref 调用
const show = () => {
  dialogVisible.value = true;
  // 打开时获取一次数据
  getList();
};

// 将 show 方法暴露出去
defineExpose({
  show
});

// ------------------------ 生命周期 ------------------------
// 组件挂载后，可以进行一些初始化，但这里由 show 方法控制
// onMounted(() => {})
</script>

<style scoped lang="scss">
.order-selection-dialog {
  padding: 0px !important;
}

.filter-card {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: center;

  .el-button {
    min-width: 80px;
  }
}

// 表格行悬停和选中样式增强
:deep(.el-table) {
  .el-table__body tr:hover > td {
    background-color: var(--el-color-primary-light-9) !important;
  }

  .current-row > td {
    background-color: var(--el-color-primary-light-8) !important;
  }
}

// 按钮图标间距
:deep(.el-icon) {
  margin-right: 4px;
}
</style>
